package 树;

import common.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * ---------------------------------------------------------
 * <h></h>
 * <p></p>
 * Created by Frank on 2021/4/12.
 * <a href="mailto:frankyao10110@gmail.com">Contact me</a>
 * ---------------------------------------------------------
 */
public class _遍历 {

    public static void main(String[] args) {
        TreeNode node = new TreeNode(7);
        node.left = new TreeNode(3);
        node.right = new TreeNode(6);
        node.left.left = new TreeNode(1);
        node.left.right = new TreeNode(2);
        node.right.left = new TreeNode(4);
        node.right.right = new TreeNode(5);

        levelOrder(node);
    }

    public static void preOrder(TreeNode node) {
        if (node == null) return;

        System.out.println(node.val);

        preOrder(node.left);
        preOrder(node.right);
    }

    public static void midOrder(TreeNode node) {
        if (node == null) return;

        midOrder(node.left);
        System.out.println(node.val);
        midOrder(node.right);
    }

    public static void inOrder(TreeNode node) {
        if (node == null) return;

        inOrder(node.left);
        inOrder(node.right);
        System.out.println(node.val);
    }

    public static void levelOrder(TreeNode node) {
        if (node == null) return;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(node);

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode pNode = queue.poll();
                assert pNode != null;
                System.out.println(pNode.val);
                if (pNode.left != null) {
                    queue.offer(pNode.left);
                }

                if (pNode.right != null) {
                    queue.offer(pNode.right);
                }
            }
        }
    }
}
